<template>
  <van-nav-bar 
    class="search-header"
    fixed 
    placeholder 
    left-arrow 
    right-text="搜索" 
    z-index="99" 
    @click-left="$router.back()" 
    @click-right="onSearch" 
  >
    <template #title>
      <form action="/">
        <van-search 
          v-model.trim="searchValue" 
          ref="search" 
          autofocus 
          :shape="shape"  
          :placeholder="placeholder" 
          @search="onSearch" 
          @clear="onClear" 
        ></van-search>
      </form>
    </template>
  </van-nav-bar>
</template>

<script>
export default {
  name: 'SearchHeader',
  props: {
    keyword: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    shape: {
      type: String,
      default: 'round',
      validator(value) {
        return ['round', 'square'].indexOf(value) !== -1
      }
    }
  },
  watch: {
    keyword(val) {
      this.searchValue = val
    }
  },
  data() {
    return {
      searchValue: this.keyword
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.search.focus()
    })
  },
  methods: {
    onSearch() {
      this.$emit('search', this.searchValue)
    },
    onClear() {
      this.searchValue = ''
      this.$emit('clear', '')
    }
  },
}
</script>

<style lang="scss" scoped>
.search-header {
  /deep/ .van-nav-bar__content {
    overflow: hidden;
  }
}
</style>